<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\admin\model\Userole;
use app\admin\model\Roles;
use think\Session;


class Index extends Base
{
	public function __construct(){
		parent::__construct();
	    $this->user_roles=new Userole();
	    $this->roles=new Roles();
	}

	// 首页信息展示
    public function index()
    {
		// 判断当前Session值是否为空
        if(!$this->current_user) {
          return $this->error('尚未登录！',url('admin/Login/index'));
        }
        $Current_url = $this->now_url;
        $id = $this->current_user['id'];
        // 传递当前登录用户的角色
        // $roles = $this->user_roles->where('userid',$id)->find();
        // $this->assign('Current_url',$Current_url);
        // $this->assign('roles',$roles);
        return $this->fetch();
    }

    // 展示当前登录用户信息
    public function showuser($id){
                $userid=$id;
                $userinfo=$this->getUserById($userid);
                // //取出当前用户分配的角色信息，只需要当前用户角色ID字段
                // $rolesid=$this->user_roles->where('userid',$userid)->column('rolesid');
                // $roles=$this->roles->where('status','1')->select();//取出角色信息
                // $this->assign('rolesid',$rolesid);
                // $this->assign('roles',$roles);
                $this->assign('userinfo',$userinfo);
                return $this->fetch();
    }

    // 修改当前用户信息
    public function updateuser($id) {
        if ($this->request->isPost()) {
            $userid=$id;
            $repassword = input('repassword');
            $data=$this->request->only(['id','username','email',
                'password',],'post');
            $data['update_at'] = $this->dataNow();            
            if($data['password'] != $repassword) {
                 return $this->error('修改失败,两次输入的密码不一致!',url('admin/Index/updateuser',['id' => $userid]));
            }
            $data['password']=$this->md5Pwd($data['password']);
            if ($this->user->update($data,['id' => $data['id']])) {
                $userinfo=$this->user->where('id',$data['id'])->find();
                Session::set('userinfo',$userinfo);
                return $this->success('修改成功!',url('admin/Index/showuser',['id' => $data['id']]));
             }else {
                 return $this->error('修改失败,可能存在相同用户名!',url('admin/Index/updateuser',['id' => $userid]));
              }
        }else {
          $userinfo=$this->getUserById($id);
          $this->assign('userinfo',$userinfo);
          return $this->fetch();
         }
    }    


}
